package com.yuezhu.fragment;

import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatSpinner;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.yuezhu.Model.DictionaryModel;
import com.yuezhu.Model.ProjectModel;
import com.yuezhu.R;
import com.yuezhu.activity.MyprojectActivity;
import com.yuezhu.adapter.MyProjectContentAdapter;
import com.yuezhu.been.UserMsg;
import com.yuezhu.citylist.CityModel;
import com.yuezhu.constante.BusAction;
import com.yuezhu.constomview.PullToRefreshView;
import com.yuezhu.control.TaskEngine;
import com.yuezhu.global.BaseFragment;
import com.yuezhu.util.LogUtils;
import com.yuezhu.util.LoginOut;
import com.yuezhu.util.MyToast;
import com.yuezhu.util.Preference;
import com.yuezhu.util.StringUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by 健 on 2016/5/21.
 */
public class MyProjectContentFragment extends BaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener {

    private List<ProjectModel> mProjectModels = new ArrayList<>();
    @InjectView(R.id.bottom_left)
    View bottom_left;
    @InjectView(R.id.bottom_middle)
    View bottom_middle;
    @InjectView(R.id.bottom_right)
    View bottom_right;
    @InjectView(R.id.spinner)
    AppCompatSpinner spinner;
    @InjectView(R.id.listview_content)
    PullToRefreshListView mListview;
    @InjectView(R.id.iv_bottome_left)
    ImageView ivBottomeLeft;
    @InjectView(R.id.iv_bottome_right)
    ImageView ivBottomeRight;
    @InjectView(R.id.et_fragment_content_search)
    EditText etFragmentContentSearch;
    @InjectView(R.id.tv_count)
    TextView tv_count;
    @InjectView(R.id.iv_notice)
    View iv_notice;
    private MyProjectContentAdapter adapter;
    public AlertDialog dialog;
    private ArrayList<String> arr;
    private int page = 0;
    private int seletedType = Integer.MAX_VALUE;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_myproject_content, null);
        ButterKnife.inject(this, view);
        arr = DictionaryModel.getInstance().getTypeNameList();
        arr.add(0, "全部类型");
        initview(view);
        initSpinner();
        setLiseners();
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("获取项目列表"); //设置内容
        builder.setCancelable(false);
        dialog = builder.create();
        dialog.show();
        TaskEngine.getInstance().startGetCityTask(queue, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject json) {
                LogUtils.e("获取项目列表" + "sec" + json.toString());
                try {
                    String respCode = json.getString("respCode");
                    if (!StringUtil.equal(respCode, "OK")) {
                        try {
                            if (json.getInt("respNo") == 999) {
                                LoginOut.LoginOut(getActivity());
                            }
                        } catch (Exception e) {
                            MyToast.showDefaltToast("获取数据失败");
                        }
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    } else {
//                        mCityModels = getCityNames();
                        JSONArray list = json.getJSONArray("cityList");
                        MyprojectActivity.mCityModels = new Gson().fromJson(list.toString(), new TypeToken<ArrayList<CityModel>>() {
                        }.getType());
                        TaskEngine.getInstance().startDataTask(queue, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject o) {
                                try {
                                    String respCode = o.getString("respCode");
                                    if (!StringUtil.equal(respCode, "OK")) {
                                        try {
                                            if (o.getInt("respNo") == 999) {
                                                LoginOut.LoginOut(getActivity());
                                            }
                                        } catch (Exception e) {
                                            MyToast.showDefaltToast("获取数据失败");
                                        }
                                        if (dialog != null) {
                                            dialog.dismiss();
                                        }
                                    } else {
                                        if (!Preference.instance(getActivity()).getString(Preference.DICTIONARY_MODEL_GRADE_JSON).equalsIgnoreCase(o.getJSONArray("dictbldgGradeList").toString())
                                                || !Preference.instance(getActivity()).getString(Preference.DICTIONARY_MODEL_GRADE_JSON).equalsIgnoreCase(o.getJSONArray("dictbldgGradeList").toString())
                                                || !Preference.instance(getActivity()).getString(Preference.DICTIONARY_LIFT_LOAD_JSON).equalsIgnoreCase(o.getJSONArray("dictliftLoadList").toString())
                                                || !Preference.instance(getActivity()).getString(Preference.DICTIONARY_LIFT_SPEED_JSON).equalsIgnoreCase(o.getJSONArray("dictliftSpeedList").toString())) {
                                            Preference.instance(getActivity()).putString(Preference.DICTIONARY_MODEL_GRADE_JSON, o.getJSONArray("dictbldgGradeList").toString());
                                            Preference.instance(getActivity()).putString(Preference.DICTIONARY_MODEL_TYPE_JSON, o.getJSONArray("dictbldgTypeList").toString());
                                            Preference.instance(getActivity()).putString(Preference.DICTIONARY_LIFT_LOAD_JSON, o.getJSONArray("dictliftLoadList").toString());
                                            Preference.instance(getActivity()).putString(Preference.DICTIONARY_LIFT_SPEED_JSON, o.getJSONArray("dictliftSpeedList").toString());
                                            if (dialog != null) {
                                                dialog.dismiss();
                                            }
                                            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  //先得到构造器
                                            builder.setTitle("提示"); //设置标题
                                            builder.setMessage("基础数据更新完成，请重新启动！"); //设置内容
                                            builder.setCancelable(false);
                                            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                    getActivity().finish();
                                                    System.exit(0);
                                                }
                                            });
                                            builder.create().show();
                                        }
                                    }
                                    page = 1;
                                    TaskEngine.getInstance().startXiangMuTask(queue, null, null, "1", ResponseLis, Errorlis);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    MyToast.showDefaltToast("获取数据失败");
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {

                            }
                        });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    MyToast.showDefaltToast("获取数据失败");
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        return view;
    }

    public void show() {
        if (dialog == null || !dialog.isShowing()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  //先得到构造器
            builder.setTitle("提示"); //设置标题
            builder.setMessage("获取项目列表"); //设置内容
            builder.setCancelable(false);
            dialog = builder.create();
            dialog.show();
            page = 1;
            TaskEngine.getInstance().startXiangMuTask(queue, null, null, "1", ResponseLis, Errorlis);
        }
    }

    public void refresh() {
        page = 1;
        TaskEngine.getInstance().startXiangMuTask(queue, null, null, "1", ResponseLis, Errorlis);
    }

    @Override
    public void initview(View view) {
        adapter = new MyProjectContentAdapter(getActivity(), queue, this);
        mListview.setAdapter(adapter);
        ivBottomeLeft.setImageResource(R.drawable.delete);
        ivBottomeRight.setImageResource(R.drawable.add);
        iv_notice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "基本版最多创建10个项目，高级版无限制。具体说明请参见菜单中的关于页面。", Toast.LENGTH_LONG).show();
            }
        });
        mListview.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        mListview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                TaskEngine.getInstance().startXiangMuTask(queue, null, null, page + "", ResponseLis, Errorlis);
            }
        });
//        addImageSpan();
//        mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(AbsListView view, int scrollState) {
//                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE &&
//                        view.getLastVisiblePosition() == view.getCount() - 1 && mProjectModels != null && mProjectModels.size() != 0) {
//                    page++;
//                    TaskEngine.getInstance().startXiangMuTask(queue, null, null, page + "", ResponseLis, Errorlis);
//                }
//            }
//
//            @Override
//            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//
//            }
//        });
    }

//    /**
//     * 图片
//     */
//    private void addImageSpan() {
//        SpannableString spanString = new SpannableString("图搜索建筑");
//        Drawable d = getResources().getDrawable(R.drawable.search);
//        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
//        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
//        spanString.setSpan(span, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        etFragmentContentSearch.setHint(spanString);
//    }

    @Override
    public void setLiseners() {
        mListview.setOnItemClickListener(this);
        ivBottomeLeft.setOnClickListener(this);
        ivBottomeRight.setOnClickListener(this);
        etFragmentContentSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String search = etFragmentContentSearch.getText().toString();
                if (TextUtils.isEmpty(search)) {
                    adapter.setList(mProjectModels);
                    adapter.notifyDataSetChanged();
                } else {
                    List<ProjectModel> tempList = new ArrayList<>();
                    for (ProjectModel model : mProjectModels) {
                        if (seletedType == Integer.MAX_VALUE) {
                            if (model.bldgName.contains(search)) {
                                tempList.add(model);
                            }
                        } else {
                            if (model.bldgName.contains(search) && model.bldgType == seletedType) {
                                tempList.add(model);
                            }
                        }
                    }
                    adapter.setList(tempList);
                    adapter.notifyDataSetChanged();
                }
            }
        });
//        TaskEngine.getInstance().startXiangMuTask(queue, "0", "1", "1", ResponseLis, Errorlis);
    }

    private void initSpinner() {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, arr) {
            @Override
            public View getDropDownView(int position, View convertView,
                                        ViewGroup parent) {
                View view = LayoutInflater.from(getContext()).inflate(R.layout.item_spinner,
                        null);
                TextView label = (TextView) view
                        .findViewById(R.id.spinner_item_label);
                label.setText(arr.get(position));
                return view;
            }
        };
        //设置显示的数据
        spinner.setAdapter(arrayAdapter);
        //注册事件
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
//                Spinner spinner = (Spinner) parent;
                spinner.setDropDownVerticalOffset(spinner.getHeight());
                if (position == 0) {
                    seletedType = Integer.MAX_VALUE;
                    adapter.setList(mProjectModels);
                    adapter.notifyDataSetChanged();
                } else {
                    seletedType = DictionaryModel.getInstance().getTypeIDByTypeNmae(arr.get(position));
                    List<ProjectModel> tempList = new ArrayList<>();
                    for (ProjectModel model : mProjectModels) {
                        if (model.bldgType == seletedType) {
                            tempList.add(model);
                        }
                    }
                    adapter.setList(tempList);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position - 1 >= 0) {
            MyprojectActivity.currentProjectModel = mProjectModels.get(position - 1);
            EventBus.getDefault().post(new BusAction.myMess());
        }
//        BusProvider.getInstance().post(new DataChangedEvent(BusAction.MYMESS));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_bottome_left:
                //联网删除项目
                adapter.setIsShowDeleteButton(!adapter.isShowDeleteButton());
                adapter.notifyDataSetChanged();
                break;
            case R.id.iv_bottome_right:
                if (UserMsg.getInstance().getLevel() == 0 && mProjectModels.size() >= 10) {
                    Toast.makeText(getActivity(), "基本版最多创建10个项目，高级版无限制。具体说明请参见菜单中的关于页面。", Toast.LENGTH_LONG).show();
                    return;
                }
                MyprojectActivity.currentProjectModel = null;
                EventBus.getDefault().post(new BusAction.myMess());
//                BusProvider.getInstance().post(new DataChangedEvent(BusAction.MYMESS));
                break;
        }
    }

    // 注册成功
    Response.Listener ResponseLis = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject json) {
            LogUtils.e("获取项目列表" + "sec" + json.toString());
            if (dialog != null) {
                dialog.dismiss();
            }
            try {
                String respCode = json.getString("respCode");
                if (!StringUtil.equal(respCode, "OK")) {
                    try {
                        if (json.getInt("respNo") == 999) {
                            LoginOut.LoginOut(getActivity());
                        }
                    } catch (Exception e) {
                        MyToast.showDefaltToast("获取数据失败");
                    }
                } else {
                    if (page > 1) {
                        List<ProjectModel> temp = new Gson().fromJson(json.getJSONArray("list").toString(), new TypeToken<List<ProjectModel>>() {
                        }.getType());
                        if (temp.size() == 0) {
                            MyToast.showDefaltToast("没有更多数据了！");
                            page--;
                        }
                        mProjectModels.addAll(temp);
                    } else {
                        mProjectModels = new Gson().fromJson(json.getJSONArray("list").toString(), new TypeToken<List<ProjectModel>>() {
                        }.getType());
                    }
                    adapter.setList(mProjectModels);
                    adapter.notifyDataSetChanged();
                    spinner.setSelection(0);
                    if (UserMsg.getInstance().getLevel() == 0) {
                        tv_count.setText(mProjectModels.size() + "/10");
                        iv_notice.setVisibility(View.VISIBLE);
                    } else {
                        tv_count.setText(mProjectModels.size() + "");
                        iv_notice.setVisibility(View.INVISIBLE);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            mListview.onRefreshComplete();
        }

    };

    /**
     * 注册失败
     */
    Response.ErrorListener Errorlis = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            LogUtils.e("项目列表失败", "error  " + volleyError.toString());
            mListview.onRefreshComplete();
        }
    };
}
